class MyBlockingQueue1{
    private  String[] data=new String[100];
    private volatile int head=0;
    private volatile int tail=0;
    private   volatile  int size=0;
    public void put(String elem) throws InterruptedException{
        synchronized (this){
            while (size==elem.length()){
                this.wait();
            }
            data[tail]=elem;
            tail++;
            if(tail==data.length ){
                tail=0;
            }
            size++;
            this.notify();
        }
    }
    public String take() throws InterruptedException{
        synchronized (this){
            while (size==0){
                this.wait();
            }
            String ret=data[head];
            head++;
            if(head==data.length){
                head=0;
            }
            size--;
            this.notify();
            return ret;
        }

    }
}



public class Test11 {
    public static void main(String[] args) {
        MyBlockingQueue1 queue=new MyBlockingQueue1();
        Thread t1 = new Thread(() -> {
            while (true) {
                try {
                    String result = queue.take();
                    System.out.println("消费元素: " + result);

                    // 暂时先不 sleep
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        // 生产者
        Thread t2 = new Thread(() -> {
            int num = 1;
            while (true) {
                try {
                    queue.put(num+"");
                    System.out.println("生产元素: " + num);
                    num++;
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        t1.start();
        t2.start();


    }
}
